package com.zhj.helloframework.mvc.processer.impl;

import com.zhj.helloframework.mvc.RequestProcessorChain;
import com.zhj.helloframework.mvc.processer.RequestProcessor;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: zhj
 * @Description: 请求预处理,包括编码以及路径处理
 * @Date: 2021/11/16 16:55
 * @Version: 1.0
 */
@Slf4j
public class PreRequestProcessor implements RequestProcessor {
    @Override
    public boolean process(RequestProcessorChain requestProcessorChain) throws Exception {
        // 1.设置请求编码，将其统一设置成utf-8
        requestProcessorChain.getRequest().setCharacterEncoding("UTF-8");
        // 2.将请求末尾的/删除，为后续匹配controller请求路径做准备
        // (一般路径为/aaa/bbb，所以当传入路径为/aaa/bbb/时需要处理成/aaa/bbb)
        String requestPath = requestProcessorChain.getRequestPath();
        if (requestPath.length()  > 1 && requestPath.endsWith("/")) {
            requestProcessorChain.setRequestPath(requestPath.substring(0,requestPath.length() - 1));
        }
        log.info("preprocess request {} {}", requestProcessorChain.getRequestMethod(), requestProcessorChain.getRequestPath());
        // 此处是请求预处理，所以需要返回true将剩下步骤交给其他处理器处理
        return true;
    }
}
